package org.example.sensor.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;

import org.example.sensor.component.JWTComponent;
import org.example.sensor.dox.User;
import org.example.sensor.exception.Code;
import org.example.sensor.exception.XException;
import org.example.sensor.service.UserService;
import org.example.sensor.vo.ResultVO;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/")

@Tag(name = "登录")
public class LoginController {
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private final JWTComponent jwtComponent;
    @Operation(summary = "登录",description = "只需输入account，password，输入id可能会引起自动生成id的冲突")
    @PostMapping("login")
    public ResultVO login(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) {
        User u = userService.getUserByaccount(user.getAccount());
        if (u == null || !passwordEncoder.matches(user.getPassword(), u.getPassword())) {
            //抛异常
            throw XException.builder().code(Code.LOGIN_ERROR).build();
        }
        String token = jwtComponent.encode(Map.of("uid", u.getId(), "role", u.getRole()));
        response.setHeader("token", token);
        response.setHeader("role", u.getRole());

        response.setHeader("Access-Control-Expose-Headers",token);


        return ResultVO.success(u);


    }
}
